using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class VFXController : MonoBehaviour
{
    [Header("Auto Details")]
    [SerializeField] private bool autoDestory = true;
    [SerializeField] private bool randomOffset = true;
    [SerializeField] private bool randomRotate = true;
    [SerializeField] private float destoryDelay = 1;
    [Header("Random Details")]
    [SerializeField] private float minXOffset = -.2f;
    [SerializeField] private float maxXOffset = .2f;
    [SerializeField] private float minYOffset = -.2f;
    [SerializeField] private float maxYOffset = .2f;
    [SerializeField] protected float minZRotate = 0f;
    [SerializeField] protected float maxZRotate = 360f;
    private float xOffset;
    private float yOffset;
    private float zRotate;

    [Header("Fade VFX Details")]
    [SerializeField] private bool canFade;
    [SerializeField] private float fadeSpeed = 1f;
    private SpriteRenderer spriteRenderer;

    private Color originalColor;
    private Coroutine coroutine;
    private void Awake()
    {
        spriteRenderer = GetComponentInChildren<SpriteRenderer>();
        originalColor = spriteRenderer.color;
    }
    private void OnEnable()
    {
        AppayRandomOffset();
        AppayRandomRotate();
        spriteRenderer.color = originalColor;
        if (autoDestory)
        {
            StartAutoDisableCoroutine();
        }
        if (canFade)
        {
            StartFadeCoroutine();
        }
    }
    private void OnDisable()
    {
        
    }
    void Start()
    {
        
    }
    private void AppayRandomOffset()
    {
        if (!randomOffset)
            return;
        xOffset = Random.Range(minXOffset, maxXOffset);
        yOffset = Random.Range(minYOffset, maxYOffset);
        transform.position += new Vector3(xOffset, yOffset, transform.position.z);
    }
    private void AppayRandomRotate()
    {
        if (!randomRotate)
            return;
        zRotate = Random.Range(minZRotate, maxZRotate);
        transform.Rotate(0, 0, zRotate);
    }
    private void StartAutoDisableCoroutine()
    {
        if (coroutine != null)
                StopCoroutine(coroutine);
            coroutine = StartCoroutine(AutoDisable());
    }
    private void StartFadeCoroutine()
    {
        StartCoroutine(FadeCo());
    }
    private IEnumerator FadeCo()
    {
        Color spriteColor = Color.white;
        while (spriteColor.a > 0)
        {
            spriteColor.a -= fadeSpeed * Time.deltaTime;
            spriteColor.a = Mathf.Max(0, spriteColor.a);
            spriteRenderer.color = spriteColor;
            yield return null;
        }
        spriteColor.a = 0;
        spriteRenderer.color = spriteColor;
    }

    private IEnumerator AutoDisable()
    {
        yield return new WaitForSeconds(destoryDelay);
        if (gameObject.activeSelf)
            PoolManager.Instance.Delease(gameObject);
    }
}
